package com.wn.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.wn.model.R;
import com.wn.model.User;
import com.wn.service.IUserService;
import com.wn.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yellow Docter
 * @date 2022 -06-10
 * @desc
 */
@RestController
public class LoginController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/auth/login")
    public R login(String username,String password) throws JsonProcessingException {

        //01 登录
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        queryWrapper.eq("password",password);

        // 支持lambda 语法
//        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//
//        // column   username 这里是值
//        lambdaQueryWrapper.eq(User::getRealName, username);
//        lambdaQueryWrapper.eq(User::getPassword, password);

        User user = userService.getOne(queryWrapper);

        if (user != null) {
            //02 生成 token
            //登录成功  通过 user 生成 token
            String token = JwtTokenUtils.createToken(user);

            return R.OK(token);
        }

        return R.ERROR();
    }
}
